package com.wmlive.hhvideo.dcijkplayerlib;

import android.content.Context;
import android.util.SparseArray;
import android.view.ViewGroup;

import com.wmlive.hhvideo.dcijkplayerlib.utils.L;

import java.io.File;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by lsq on 7/5/2017.
 * 单例的IjkPlayer
 */

public class DcIjkPlayerManager {
    private DcIjkPlayer dcIjkPlayer;
    private DcIjkPlayer cachePlayer;
    private Context context;
    private int randomId = 0;
    private SparseArray<IjkPlayListener> listenerArray;

    private static final class Holder {
        final static DcIjkPlayerManager HOLDER = new DcIjkPlayerManager();
    }

    public static DcIjkPlayerManager get() {
        return Holder.HOLDER;
    }

    /**
     * 初始化IjkPlayer播放器
     *
     * @param context
     */
    public void init(Context context) {
        this.context = context.getApplicationContext();
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        listenerArray = new SparseArray<>();
        initPlayer();
    }

    private void initPlayer() {
        if (context != null) {
            dcIjkPlayer = new DcIjkPlayer(context.getApplicationContext());
            dcIjkPlayer.setPlayListener(listener);
        }
    }

    public DcIjkPlayer getPlayer() {
        return dcIjkPlayer;
    }

    /**
     * 设置缓存的文件
     * 如果{@link DcIjkPlayer #canCache}为true，不设置缓存文件会默认使用app的内部缓存目录
     *
     * @param cacheFile
     */
    public void setCacheFile(File cacheFile) {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.setCacheFile(cacheFile);
        }
    }

    /**
     * 设置刷新当前播放位置的时间间隔，默认是1s
     *
     * @param refreshInterval
     */
    public void setRefreshInterval(int refreshInterval) {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.setRefreshInterval(refreshInterval);
        }
    }

    /**
     * 设置是否可缓存
     *
     * @param canCache
     */
    public void setCacheable(boolean canCache) {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.setCacheable(canCache);
        }
    }

    public void setCanLoop(boolean canLoop) {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.setCanLoop(canLoop);
        }
    }

    /**
     * 点击播放器暂停，再次点击播放
     *
     * @param clickPause
     */
    public void setClickPause(boolean clickPause) {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.setClickPause(clickPause);
        }
    }

    public void setPlayListener(int videoType, IjkPlayListener ijkPlayListener) {
        listenerArray.put(videoType, ijkPlayListener);
    }

    public void attachPlayer(ViewGroup container, OnPlayerDetachListener listener) {
        if (dcIjkPlayer == null) {
            initPlayer();
        }
        if (dcIjkPlayer != null) {
            ViewGroup viewGroup = (ViewGroup) dcIjkPlayer.getParent();
            if (viewGroup != null) {
                viewGroup.removeAllViews();
                if (listener != null) {
                    listener.onDetach();
                }
                L.i("====从父布局移除Player：" + viewGroup);
            }
            container.removeAllViews();
            container.addView(dcIjkPlayer);
            L.i("====附加Player:" + container);
        }
    }

    /**
     * 设置视频的url
     *
     * @param randomId 随机值，用于区分是哪个页面
     * @param videoId  视频的id
     * @param url      视频Url
     */
    public void setVideoUrl(int randomId, long videoId, String url) {
        this.randomId = randomId;
        if (dcIjkPlayer == null) {
            initPlayer();
        }
        if (dcIjkPlayer != null) {
            dcIjkPlayer.setVideoUrl(videoId, url);
        }
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        if (dcIjkPlayer != null) {
            return dcIjkPlayer.isPlaying();
        }
        return false;
    }

    /**
     * 获取当前播放的url
     *
     * @return
     */
    public String getUrl() {
        if (dcIjkPlayer != null) {
            return dcIjkPlayer.getUrl();
        }
        return null;
    }

    public void resetUrl() {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.resetUrl();
        }
    }

    /**
     * 开始播放
     */
    public void startPlay() {
        if (dcIjkPlayer == null) {
            initPlayer();
        }
        if (dcIjkPlayer != null) {
            dcIjkPlayer.startPlay();
        }
    }

    /**
     * 暂停播放
     */
    public void pausePlay() {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.pausePlay();
        }
    }

    /**
     * 恢复播放
     *
     * @param randomId
     */
    public void resumePlay(int randomId) {
        this.randomId = randomId;
        if (dcIjkPlayer == null) {
            initPlayer();
        }
        if (dcIjkPlayer != null) {
            dcIjkPlayer.resumePlay();
        }
    }

    /**
     * 停止播放，此方法会释放掉IMediaPlayer
     */
    public void stopPlay() {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.stopPlay();
        }
    }

    /**
     * 释放播放器
     *
     * @param cleartargetstate
     */
    public void releasePlayer(boolean cleartargetstate) {
        listenerArray.remove(randomId);
        listenerArray.size();
        L.i("====释放videoType：" + randomId);
        this.randomId = 0;
        if (dcIjkPlayer != null) {
            dcIjkPlayer.resetUrl();
            ViewGroup viewGroup = (ViewGroup) dcIjkPlayer.getParent();
            if (viewGroup != null) {
                viewGroup.removeAllViews();
                L.i("====从父布局移除Player：" + viewGroup);
            }
//            dcIjkPlayer.releasePlayer(cleartargetstate);
        }
        if (cachePlayer != null) {
            cachePlayer.release(true);
        }
    }


    /**
     * 挂起播放器，此方法会释放掉IMediaPlayer，但是不会清除播放状态
     */
    public void suspendPlay() {
        if (dcIjkPlayer != null) {
            dcIjkPlayer.suspendPlay();
        }
    }

    private AbsIjkPlayListener listener = new AbsIjkPlayListener() {
        @Override
        public void onPlayStart() {
            super.onPlayStart();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayStart();
            }
        }

        @Override
        public void onPlayStop() {
            super.onPlayStop();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayStop();
            }
        }

        @Override
        public void onPlayPause() {
            super.onPlayPause();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayPause();
            }
        }

        @Override
        public void onPlayResume() {
            super.onPlayResume();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayResume();
            }
        }

        @Override
        public void onPlayError(int errorCode) {
            super.onPlayError(errorCode);
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayError(errorCode);
            }
        }

        @Override
        public void onPlayCompleted() {
            super.onPlayCompleted();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayCompleted();
            }
        }

        @Override
        public void onPlayBufferStart() {
            super.onPlayBufferStart();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayBufferStart();
            }
        }

        @Override
        public void onPlayBufferEnd() {
            super.onPlayBufferEnd();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayBufferEnd();
            }
        }

        @Override
        public void onPlayPreparing() {
            super.onPlayPreparing();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayPreparing();
            }
        }

        @Override
        public void onPlayPrepared() {
            super.onPlayPrepared();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayPrepared();
            }
        }

        @Override
        public void onAudioRenderingStart() {
            super.onAudioRenderingStart();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onAudioRenderingStart();
            }
        }

        @Override
        public void onVideoRenderingStart() {
            super.onVideoRenderingStart();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onVideoRenderingStart();
            }
        }

        @Override
        public void onVideoRotationChanged(int rotate) {
            super.onVideoRotationChanged(rotate);
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onVideoRotationChanged(rotate);
            }
        }

        @Override
        public void onPlayingPosition(long position) {
            super.onPlayingPosition(position);
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayingPosition(position);
            }
        }

        @Override
        public void onFileError(int code, String errorMessage) {
            super.onFileError(code, errorMessage);
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onFileError(code, errorMessage);
            }
        }

        @Override
        public void onLoopStart() {
            super.onLoopStart();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onLoopStart();
            }
        }

        @Override
        public void onClickPause() {
            super.onClickPause();
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onClickPause();
            }
        }

        @Override
        public void onPlayTimeCompleted(long videoId, String url, int videoDuring) {
            super.onPlayTimeCompleted(videoId, url, videoDuring);
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onPlayTimeCompleted(videoId, url, videoDuring);
            }
        }

        @Override
        public void onDoubleClick(float x, float y) {
            super.onDoubleClick(x, y);
            if (listenerArray.get(randomId) != null) {
                listenerArray.get(randomId).onDoubleClick(x, y);
            }
        }
    };

    public interface OnPlayerDetachListener {
        void onDetach();
    }
}